<template>
  <div class="app-container">
    <div class="filter-container">
      <!-- <el-input
        v-model="listQuery.uloc"
        placeholder="请选择报工点"
        style="width: 200px;"
        class="filter-item"
      /> -->
      <el-cascader v-model="listQuery.uloc" :options="options" :props="{value:'id', label:'name'}" :show-all-levels="false" placeholder="请选择报工点" class="filter-item" clearable></el-cascader>
      过点时间:
      <el-date-picker
        v-model="listQuery.datetime"
        type="datetimerange"
        format="yyyy-MM-dd HH:mm"
        start-placeholder="开始时间"
        end-placeholder="结束时间"
        class="filter-item"
        @change="dateChange">
      </el-date-picker>
      <el-select v-model="listQuery.proType" placeholder="请选择总装车型" clearable style="width: 150px" class="filter-item">
        <el-option v-for="item in proTypeList" :key="item.codeValue" :label="item.name" :value="item.codeValue" />
      </el-select>
      <el-select v-model="listQuery.saleType" placeholder="请选择销售类型" clearable style="width: 150px" class="filter-item">
        <el-option v-for="item in saleTypeList" :key="item.codeValue" :label="item.name" :value="item.codeValue" />
      </el-select>
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">查询</el-button>
      <el-button class="filter-item" type="info" icon="el-icon-refresh" @click="handleReset">重置</el-button>
      <el-button v-waves style="float:right;" class="filter-item" type="primary" icon="el-icon-download" @click="handleExport">
        导出
      </el-button>
    </div>
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
    >
      <el-table-column align="center" label="vin号" prop="vin" />
      <el-table-column align="center" label="工厂" prop="plant" />
      <el-table-column align="center" label="车间" prop="workShop" />
      <el-table-column align="center" label="报工点" prop="uloc" />
      <el-table-column align="center" label="物料号" prop="materialNo" />
      <el-table-column align="center" label="操作人" prop="userName" />
      <el-table-column align="center" label="过点时间" prop="scanTime" />
      <el-table-column align="center" label="总装车型" prop="proType" >
        <template slot-scope="scope">
          <div>{{ scope.row.proType | proTypeFilter }}</div>
        </template>
      </el-table-column>
      <el-table-column align="center" label="销售类型" prop="saleType" >
        <template slot-scope="scope">
          <div>{{ scope.row.saleType | saleTypeFilter }}</div>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="fetchData" />
  </div>
</template>
<script>
import { fetchList, fetchUlocList, fetchTypeList } from '@/api/production/router-log-query'
import { fetchCode } from '@/api/sys/sys-code'
import waves from '@/directive/waves' // waves directive
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import axios from "axios"
import underscore from 'underscore'
import { parseTime } from '@/utils'

let saleTypeList, proTypeList
export default {
  name: 'RouterLogQuery',
  directives: { waves },
  components: { Pagination },
  filters: {
    saleTypeFilter(type) {
      return type ? saleTypeList.find(a => a.codeValue === type).name : ''
    },
    proTypeFilter(type) {
      return type ? proTypeList.find(a => a.codeValue === type).name : ''
    }
  },

  data() {
    return {
      // 查询
      listQuery: {
        page: 1,
        limit: 10,
        uloc: [],
        datetime: null,
        saleType: undefined,
        proType: undefined
      },
      saleTypeList: [],
      proTypeList: [],
      options: [],
      // 表格
      list: null,
      total: 0,
      listLoading: false,
      // 导出
      downloadLoading: false
    }
  },
  created() {
    // 默认日期
    const year = new Date().getFullYear()
    const month = new Date().getMonth()
    const day = new Date().getDate()
    this.listQuery.datetime = [new Date(year, month, day), new Date(year, month, day + 1)]
    // 报工点
    fetchUlocList().then(res => {
      this.options = res.data
    })
    // 获取销售类型和总装车型
    axios.all([fetchCode('Key_Sale_Type'), fetchTypeList()]).then(
      axios.spread((res1, res2) => {
        saleTypeList = res1.data
        proTypeList = res2.data
        // 用于查询条件
        this.saleTypeList = saleTypeList
        this.proTypeList = proTypeList
      })
    )
  },
  methods: {
    fetchData() {
      // 提交验证
      if (this.listQuery.uloc.length === 0 && !this.listQuery.datetime) {
        this.$message.warning('请选择报工点或时间范围')
        return
      }
      this.listLoading = true
      const data = underscore.omit(this.listQuery, 'datetime', 'uloc')
      if (this.listQuery.datetime !== null) {
        data.beginDate = parseTime(this.listQuery.datetime[0], '{y}-{m}-{d} {h}:{i}')
        data.endDate = parseTime(this.listQuery.datetime[1], '{y}-{m}-{d} {h}:{i}')
      }
      if (this.listQuery.uloc.length !== 0) {
        data.uloc = this.listQuery.uloc[2]
      }
      fetchList(data).then(res => {
        this.list = res.data.list
        this.total = res.data.total
        this.listLoading = false
      })
    },
    handleFilter() {
      this.fetchData()
    },
    handleReset() {
      this.listQuery = {
        page: 1,
        limit: 10,
        uloc: [],
        datetime: null,
        saleType: undefined,
        proType: undefined
      }
    },
    dateChange(date) {
      if (date) {
        const startDate = date[0]
        const endDate = date[1]
        if (endDate.valueOf() - startDate.valueOf() > 60 * 24 * 60 * 60 * 1000) {
          this.$message.warning('时间范围超过了60天，请重新选择！')
          this.listQuery.datetime = null
          return
        }
      }
    },
    // 导出
    handleExport() {
      this.downloadLoading = true
      const data = underscore.omit(this.listQuery, 'datetime', 'uloc')
      if (this.listQuery.datetime !== null) {
        data.beginDate = parseTime(this.listQuery.datetime[0], '{y}-{m}-{d} {h}:{i}')
        data.endDate = parseTime(this.listQuery.datetime[1], '{y}-{m}-{d} {h}:{i}')
      }
      if (this.listQuery.uloc.length !== 0) {
        data.uloc = this.listQuery.uloc[2]
      }
      data.page = -1
      data.limit = -1
      fetchList(data).then(res => {
        if (res.code == 200) {
          import('@/vendor/Export2Excel').then(excel => {
            const header = ['vin号', '工厂', '车间', '报工点', '物料号', '操作人', '过点时间', '总装车型', '销售类型']
            const keys = ['vin', 'plant', 'workShop', 'uloc', 'materialNo', 'userName', 'scanTime', 'proType', 'saleType']
            const data = this.formatList(res.data, keys).map(v => underscore.values(v))
            excel.export_json_to_excel({
              header,
              filename: '过点' + new Date().valueOf(),
              data
            })
            this.downloadLoading = false
          })
          
        } else {
          this.$message.error('服务器内部错误！');
        }
        this.listLoading = false
      })
    },
    formatList(list, keys) {
      const newList = []
      for (const i of list) {
        const item = {}
        for (const j of keys) {
          if (j === 'saleType') {
            item[j] = saleTypeList.find(a => a.codeValue === i[j]).name
            continue
          }
          if (j === 'proType') {
            item[j] = proTypeList.find(a => a.codeValue === i[j]).name
            continue
          }
          item[j] = i[j]
        }
        newList.push(item)
      }
      return newList
    }
  }
}
</script>
